package com.redtree.air.db
{
	import com.redtree.air.components.lib.StockCellRenderer;
	import com.redtree.air.components.libas.CellColorIFactory;
	
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.ClassFactory;

	public class Stocks extends Model
	{
		private var stockFieldNames:Array = new Array('股票代号','股票名称','开盘','昨收价','当前价','最高价','最低价','叫买','叫卖','成交数','成交金额','买一股','买一价','买二股','买二价','买三股','买三价','买四股','买四价','买五股','买五价','卖一股','卖一价','卖二股','卖二价','卖三股','卖三价','卖四股','卖四价','卖五股','卖五价','更新日期','更新时间','涨跌幅度');
		public function Stocks()
		{
			super();			
			dataGridColumnsAry = [['code','代码'],['name','名称'],['num','数量'],['im','买入价'],['om','卖出价'],['dateInsert','记录时间']];
			tableName = getTableName('stockio');
		}
		public function getStocks(offset:int=0,limit:int=DEFAULT_PAGE_SIZE,underSecurity:Boolean=true,justCurrentLevel:Boolean=false):Array
		{
			var sql:String = "select * from stockio as s";
			if( underSecurity )
				sql += " where s.security_level "+(justCurrentLevel?"=":"<=")+" "+currentSecurityLevel;
			sql += " order by id desc";
			if( limit )
				sql += " limit "+(limit)+" offset "+(offset-1)*limit;
			return _getStocksBySql(sql);

		}
		public function getLevelReferData(offset:int=0,limit:int=DEFAULT_PAGE_SIZE):Array
		{
			return getStocks(offset,limit,true,true);
		}
		public function getReferTotalCount():int
		{
			return getTotalCount(true,true);
		}
		public function getTotalCount(underSecurity:Boolean=true,justCurrentLevel:Boolean=false):int{
			var sql:String = "select count(*) as num from contacts as c";
			if( underSecurity )
				sql += " where c.security_level "+(justCurrentLevel?"=":"<=")+" "+currentSecurityLevel;
			Model.instance.query(sql);
				
			return Model.instance.data[0]['num'];
			
		}
		/**
		 * 得到自选股票字段名字
		 */
		public function getSelfStockFieldNames():Array
		{
			var fieldKeys:Array = this._getConfigStockFields();
			return this.getStockFieldNames(fieldKeys);
		}
		/**
		 * 删除自选股
		 */
		public function delSelfStock(code:String):Boolean
		{
			var sql:String = "delete from self_stock where code=\""+code+'"';
			return Model.instance.query(sql);
		}

		/**
		 * 
		 * 得到股票名字fieldNames
		 */
		public function getStockFieldNames(fieldKeys:Array=null, fullField:Boolean=false):Array
		{
			
			var fieldNames:Array = new Array();
			for( var i:int=0; i< stockFieldNames.length; i++ ){
				if( int(fieldKeys[i]) == 1 ) fieldNames.push(new Array('field_'+i,stockFieldNames[i]));
			}
			return this._getDataGridColumns(fieldNames,40);
		}
		private function _getDataGridColumns(tmpColumns:Array=null, fixedWidth:int=0 ):Array
		{
			var cols:Array = super.getDataGridColumns(tmpColumns, fixedWidth);
			var colorFields:Array = new Array ('field_4','field_5','field_6',Constant.STOCK_INCREASE_FIELD);
//			var itemRenderer:CellColorIFactory = new CellColorIFactory(this._setCellColor);
			for( var i:int=0; i<cols.length; i++ ){
				// 加色
				if( colorFields.indexOf(DataGridColumn(cols[i]).dataField)>-1 )
				{
					DataGridColumn(cols[i]).itemRenderer = new ClassFactory(StockCellRenderer);
//					DataGridColumn(cols[i]).itemRenderer = itemRenderer;
				}
			}
			return cols;
		}
		/**
		 * 设置单元格颜色
		 */
		private function _setCellColor(field:String, value:Array):uint
		{
			if(value[Constant.STOCK_STOPPED_PRICE_FIELD]){
				if(value[Constant.STOCK_STOPPED_PRICE_FIELD] < value[field]){ 
					return 0xFF0000;
				}
				else if( value[Constant.STOCK_STOPPED_PRICE_FIELD] > value[field]){
					return 0x056A05;
				}
			}
			return 0x0B333C;
		}
		/**
		 * 得到自选股code String
		 */
		public function getSelfStockCodes():String
		{
			var sql:String = 'select code from self_stock';
			if(Model.instance.query(sql))var result:Array = Model.instance.data;
			var resultString:String = '';
			for( var i:int=0; i<result.length; i++ )
				if(result[i]['rows']==null)
					if( i== 0 )resultString = result[i]['code'];
					else resultString += ','+result[i]['code'];
			return resultString;
		}
		/**
		 * 得到搜索股票fieldNames
		 * lyzy,11,000558,sz000558,莱茵置业,lyzy;
		 */
		public function getSearchStockFields():Array
		{
			var fieldNames:Array = [['field_0','拼音'],['field_2','代码'],['field_4','名称']];
			return this.getDataGridColumns(fieldNames);			
		}
		public function getTransStockFields():Array
		{
			var fieldNames:Array = [['field_0','代码'],['field_1','名称'],['field_2','数量'],['field_3','买入价'],['field_4','卖出价'],['field_5','记录时间']];
			return this.getDataGridColumns(fieldNames);
		}
		/**
		 * 解析搜索股票数据
		 * return Array( Array('field_0'=>data,...) )
		 */
		public function parseSearchData(s:String):Array
		{
			trace('in parseSearchData, string='+s);
			var ary:Array = s.split(';');
			return this._parseData(ary);
		}
		/**
		 * 保存字段配置信息
		 */
		public function saveStockFields( str:String ):Boolean
		{
			var sql:String = "update config set value=\""+str+'" WHERE key="stock_fields"';
			return Model.instance.query(sql);
		}

		/**
		 * 解析自选股票数据
		 * return Array( Array('field_0'=>data,...) )
		 */
		public function parseSelfStockData(s:String):Array
		{
			trace('in parseSelfStockData, string='+s);
//			var pattern:RegExp
			function aa(el:*, i:int, arr:Array):void {
				arr[i] = ary2[i]+','+String(el).replace(/"(.*)"/gi,"$1");
				arr[i] += ',0';//涨幅
			}
			function bb(el:*, i:int, arr:Array):void {
				arr[i] = String(el).replace(/hq_str_(.*)=/gi,"$1");
			}
			var pattern:RegExp = /"(.*)"/gi;
			var ary:Array = s.match(pattern);
			var ary2:Array = s.match(/hq_str_.*=/gi);
			ary2.forEach(bb);
			ary.forEach(aa);
			return this._parseData(ary);
		}
		/**
		 * 添加自选股票
		 */
		public function addSelfStock( code:String, name:String, numBuy:int, price:Number, securityLevel:int ):Boolean
		{
			var ss:Array = this.getSelfStockByCode(code);
			if( ss.length > 0 ) return false;
			var sql:String = "insert into self_stock (code,name,num,price,security_level) VALUES " + 
				'("'+code+'","'+name+'",'+numBuy+','+price+','+securityLevel+')';
			var result:Boolean = Model.instance.query(sql);
			if( result && numBuy > 0){
				// 添加交易记录
				this.addStockTransaction(code,name,numBuy,0,numBuy*price,securityLevel);
			}
			return result;
		}
		public function getSelfStockByCode(code:String):Array
		{
			var sql:String = 'select * from self_stock where code ="'+code+'"';
			if(Model.instance.query(sql))var result:Array = Model.instance.data;
			var resultAry:Array = new Array();
			if(result[0]['rows']==null)resultAry.push(result[0]);
			return resultAry;
		}
		/**
		 * 增加交易记录
		 */
		public function addStockTransaction( code:String, name:String, num:int, inMoney:Number, outMoney:Number, securityLevel:int ):Boolean
		{
			var sql:String = "insert into stockio (code,name,num,im,om,security_level) VALUES " + 
				'("'+code+'","'+name+'",'+num+',"'+inMoney+'","'+outMoney+'",'+securityLevel+')';
			return Model.instance.query(sql);
		}
		/**
		 * public 
		 * 获得自选股票字段的显示配置
		 * return Array for datagrid
		 */
		public function getStockConfigFields():Array
		{
			var fieldsValue:Array = this._getConfigStockFields();
			var result:Array = new Array();
			for( var i:int=0; i<fieldsValue.length; i++ ){
				var s:Array = new Array();
				s['name'] = stockFieldNames[i];
				s['show'] = fieldsValue[i] == 1;
				result.push(s);
			}
			return result;
		}
		/**
		 * private
		 * 得到数据库里存储的自选股票是否显示数据
		 */
		private function _getConfigStockFields():Array
		{
			var sql:String = "select key,value from config where key=\"stock_fields\" limit 1";
			var result:Array = [];
			if(Model.instance.query(sql)) result = Model.instance.data;
			result =  String(result[0]['value']).split(','); 
			var n:int = stockFieldNames.length - result.length;
			if( n > 0 )for(var i:int=0; i<n; i++ )result.push('1');
			return result;
		}
		/**
		 * @access private
		 * 返回数据
		 */
		private function _parseData(ary:Array):Array
		{
			var result:Array = new Array();
			for( var i:int=0; i< ary.length; i++ )
			{
				var ary2:Array = String(ary[i]).split(',');
				var tmpAry:Array = new Array();
				for( var j:int=0; j<ary2.length; j++ )
				{
					tmpAry['field_'+j] = ary2[j];
				}
				result.push(tmpAry);
			}
			return result;
		}	
		private function _getStocksBySql(sql:String):Array
		{
			if(Model.instance.query(sql))var result:Array = Model.instance.data;
			var resultAry:Array = new Array();
			for( var i:int=0;i<result.length; i++ )
				resultAry.push(new Stock(result[i]));
			return resultAry;
		}
	}
}